To analyze the differences and applications of [] List Array ArrayList in C
- 2020-06-07 05:10:51
- OfStack
[] is for a specific type, fixed length.
List is type-specific and of arbitrary length.
Array is for any type, fixed length.
ArrayList is for any type, any length.
Array and ArrayList implement any type by storing object, so they are converted when used.
The sample application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// System.Int32 Is the structure
int[] arr = new int[] { 1, 2, 3 };
Response.Write(arr[0]); // 1
Change(arr);
Response.Write(arr[0]); // 2
// List The namespace of is System.Collections.Generic
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
Response.Write(list[0]); // 1
Change(list);
Response.Write(list[0]); // 2
// Array The namespace of is System
Array array = Array.CreateInstance(System.Type.GetType("System.Int32"), 3); // Array Is an abstract class and cannot be used new Array To create.
array.SetValue(1, 0);
array.SetValue(2, 1);
array.SetValue(3, 2);
Response.Write(array.GetValue(0)); // 1
Change(array);
Response.Write(array.GetValue(0)); // 2
// ArrayList The namespace of is System.Collections
ArrayList arrayList = new ArrayList(3);
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
Response.Write(arrayList[0]); // 1
Change(arrayList);
Response.Write(arrayList[0]); // 2
}
private void Change(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] *= 2;
}
}
private void Change(List<int> list)
{
for (int i = 0; i < list.Count; i++) // use Count
{
list[i] *= 2;
}
}
private void Change(Array array)
{
for (int i = 0; i < array.Length; i++) // use Length
{
array.SetValue((int)array.GetValue(i) * 2, i); // Type conversion is required
}
}
private void Change(ArrayList arrayList)
{
for (int i = 0; i < arrayList.Count; i++) // use Count
{
arrayList[i] = (int)arrayList[i] * 2; // Type conversion is required
}
}
}
In addition.
Converting 1 object array to ArrayList USES the ArrayList.Adapter method. This method wraps 1 IList in 1 ArrayLIst.
Person[] personArray = myPerson.GetPersons();
ArrayList personList = ArrayList.Adapter(personArray);
Converting an ArrayList to an array of objects can use the ArrayList.ToArray method.
Person[] personArrayFromList = (Person[])personList.ToArray(typeof(Person));
Don't forget to cast before calling the ArrayList.ToArray method, otherwise an error will occur at compile time indicating that you cannot convert 1 ArrayList to an array of Person objects.